package com.zimmor.mogodb;

import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.BasicBSONObject;
import org.bson.Document;
import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:zimmor
 * @Date: 2021/3/4 16:40
 * @Description
 * @version: 1.0.0
 */

public class Demo1 {
    @Test
    /**
     * mongoDB新增数据，单个新增
     */
    public void fun1() {
        //获取客户端
        MongoClient client = new MongoClient("192.168.204.128");
        //获取数据库
        MongoDatabase spitdb = client.getDatabase("spitdb");
        //获取collection
        MongoCollection<Document> spit = spitdb.getCollection("spit");
        //进行操作，新增五条数据
        Map<String, Object> map = new HashMap();
        for (int i = 0; i < 5; i++) {
            map.put("_id", i);
            map.put("content","赚钱"+i);
            map.put("visits",i*15);
            spit.insertOne(new Document(map));
            map.clear();
        }
        //断开客户端
    }

    @Test
    /**
     * mongoDb ,批量新增数据
     */
    public void fun2() {
        //获取客户端
        MongoClient client = new MongoClient("192.168.204.128");
        //获取数据库
        MongoDatabase spitdb = client.getDatabase("spitdb");
        //获取Collection
        MongoCollection<Document> spit = spitdb.getCollection("spit");
        //进行批量新增操作
        Map<String, Object> map = new HashMap<String, Object>();
        List list = new ArrayList();
        for (int i = 5; i < 10; i++) {
            map.put("_id", i);
            map.put("content","赚钱"+i);
            map.put("visits",i*15);
            list.add(new Document(map));
        }
        spit.insertMany(list);
        //断开客户端
        client.close();
    }

    @Test
    /**
     *根据条件进行获取
     */
    public void fun3() {
        MongoClient client = new MongoClient("192.168.204.128");
        MongoDatabase spitdb = client.getDatabase("spitdb");
        MongoCollection<Document> spit = spitdb.getCollection("spit");
//        BasicDBObject bson=new BasicDBObject("visits",45);
//        BasicDBObject bson=new BasicDBObject("visits", new BasicDBObject("$gt",15));
//        BasicDBObject bson=new BasicDBObject(new BasicDBObject("$and",new BasicDBObject[]{new BasicDBObject("visits", new BasicDBObject("$gt",15)),new BasicDBObject("visits", new BasicDBObject("$lt",100))}));
        BasicDBObject bson = new BasicDBObject();
        bson.put("visits", new BasicDBObject("$gt",15));
        FindIterable<Document> documents = spit.find(bson);
        for(Document document: documents) {
            System.out.println(document.getString("content"));
            System.out.println(document.getInteger("visits"));
        }
        client.close();
    }
}
